package cn.echo.consul.manager.controller;

import cn.echo.consul.manager.annotation.RequestPermissions;
import cn.echo.consul.manager.entity.KeyValueItem;
import cn.echo.consul.manager.entity.KeyValueRecord;
import cn.echo.consul.manager.service.KeyValueItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.echo.consul.manager.constant.HeaderFields.AUTH_USER_ID;
import static cn.echo.consul.manager.enums.PermissionRole.*;
import static cn.echo.consul.manager.enums.PermissionRole.VIEWER;

/**
 * KeyValue配置管理
 * @author lonyee
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/kv/")
public class KeyValueItemController {

	final KeyValueItemService keyValueItemService;

	/**
	 * 获取KeyValue配置列表
	 */
	@RequestPermissions({ ADMIN, OWNER, PARTNER, VIEWER })
	@GetMapping("/items")
	public List<KeyValueItem> getKeyValueItems(String projectId, String env) {
		List<KeyValueItem> list = keyValueItemService.getKeyValueItems(projectId, env);
		return list;
	}

	/**
	 * 保存KeyValue配置信息
	 */
	@RequestPermissions({ OWNER, PARTNER })
	@PostMapping("/save")
	public void save(@RequestAttribute(AUTH_USER_ID) String userId,
					 String projectId, String env, String key, String value) {
		keyValueItemService.modifyKeyValueItem(userId, projectId, env, key, value);
	}

	/**
	 * 保存KeyValue配置YAML信息
	 */
	@RequestPermissions({ OWNER, PARTNER })
    @PostMapping("/yaml/save")
    public void saveYaml(@RequestAttribute(AUTH_USER_ID) String userId,
						 String projectId, String env, String yamlSource, Boolean replace) {
        keyValueItemService.modifyKeyValueYml(userId, projectId, env, yamlSource, replace);
    }

	/**
	 * 移除KeyValue配置信息
	 */
	@RequestPermissions({ OWNER, PARTNER })
	@PostMapping("/remove")
	public void remove(@RequestAttribute(AUTH_USER_ID) String userId,
					 String projectId, String env, String key) {
		keyValueItemService.removeKeyValueItem(userId, projectId, env, key);
	}

	/**
	 * KeyValue配置YAML格式化
	 */
	@RequestPermissions({ OWNER, PARTNER })
	@PostMapping("/yaml/format")
	public void formatYaml(String projectId, String env) {
		keyValueItemService.formatYaml(projectId, env);
	}

	/**
	 * KeyValue配置YAML格式信息
	 */
	@RequestPermissions({ ADMIN, OWNER, PARTNER, VIEWER })
	@GetMapping("/yaml")
	public String yaml(String projectId, String env) {
		String yaml = keyValueItemService.getYaml(projectId, env);
		return yaml;
	}

	/**
	 * 获取KeyValue配置历史记录
	 */
	@RequestPermissions({ ADMIN, OWNER, PARTNER, VIEWER })
	@GetMapping("/records")
	public List<KeyValueRecord> getKeyValueRecords(String projectId, String env, String key) {
		List<KeyValueRecord> list = keyValueItemService.getKeyValueRecords(projectId, env, key);
		return list;
	}
}
